package com.birth.memo.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.DatePicker.OnDateChangedListener;

import com.birth.memo.R;
import com.birth.memo.util.Constants;
import com.birth.memo.util.DateBean;

public class ViewMemoList extends Activity{
	
	private static final int DIALOG_ADD_MEMO = 1;
	
	private static final int DIALOG_EDIT_MEMO = 0;
	
	
	private static final int MENU_DEL = 2;
	private static final int MENU_EDIT = 3;
	
	
	
	private ListView listView;
	
	private Context context;
	
	private EditText txtName;
	
	private DatePicker datePicker;

	private RadioButton chinaDay;
	
	private RadioButton commonDay;
	
	private RadioGroup radioGroup;
	
	private int birthdayType;
	
	private View textEntryView;
	
	private long curId;
	
	private int mYear = 1980;
    private int mMonth = 0;
    private int mDay = 1;
	
	private OnDateChangedListener onDateChangedListener = new OnDateChangedListener(){
		@Override
		public void onDateChanged(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;		
			
			if(year>2025 || year<1930){
				Toast.makeText(context, "年份需要在1930-2025之间！", Toast.LENGTH_SHORT).show();
			}
			if(year>2025){
				mYear = 2025;
			}
			if(year<1930){
				mYear = 1930;
			}
				
		}
		
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);		
		this.setContentView(R.layout.view_memo_list);
		context = getApplicationContext();
		listView = (ListView)this.findViewById(R.id.memoList);	
		
		refreshData();
	
	}
	
	private void refreshData(){		
	    Cursor c = getContentResolver().query(Constants.URI_MEMO, null, null, null, null);
	    startManagingCursor(c);	   
	    ListAdapter adapter = new SimpleCursorAdapter(this,
	            R.layout.memo_list_item, c, 
	                    new String[] { "person_name", "birth_yin","birth_yang"}, 
	                    new int[] { R.id.person_name, R.id.yin,R.id.yang });
	    listView.setAdapter(adapter);
	    listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> adapterView, View view,
					int position, long id) {
				curId = id;
				registerForContextMenu(adapterView);
				return false;
			}			
		});
	}
	
	private void initBirthdayPick(){
		Cursor c = getContentResolver().query(Constants.URI_MEMO, null, "_id = ?", new String[]{String.valueOf(curId)}, null);
	    startManagingCursor(c);	  
	    if(c.moveToFirst()){
	    	String name = c.getString(c.getColumnIndex("person_name"));
	    	String birth_yin = c.getString(c.getColumnIndex("birth_yin"));
	    	String birth_yang = c.getString(c.getColumnIndex("birth_yang"));	    	
	    	int flag = Integer.valueOf(c.getString(c.getColumnIndex("flag")));
	    	
	    	txtName.setText(name);
	    	
	    	if(flag ==Constants.CHINA_TYPE){
	    		chinaDay.setChecked(true);
	    		int year = Integer.valueOf(birth_yin.substring(0,4));
		    	int month = Integer.valueOf(birth_yin.substring(5,7));
		    	int day = Integer.valueOf(birth_yin.substring(8,10));
	    		datePicker.updateDate(year, month-1, day);
	    	}else{
	    		commonDay.setChecked(true);
	    		int year = Integer.valueOf(birth_yang.substring(0,4));
		    	int month = Integer.valueOf(birth_yang.substring(5,7));
		    	int day = Integer.valueOf(birth_yang.substring(8,10));
	    		datePicker.updateDate(year, month-1, day);
	    	}
	    }	    
	
	}
	
	private void clearBirthdayPick(){
		txtName.setText("");
		chinaDay.setChecked(true);
		datePicker.updateDate(1980, 0, 1);
	}
	
	
	
	@Override
    protected void onPrepareDialog(int id, Dialog dialog) {
	   	
        switch (id) {
            case DIALOG_EDIT_MEMO:
            	initBirthdayPick();
                break;    
            case DIALOG_ADD_MEMO:
            	clearBirthdayPick();
            	break;
        }
    } 
	
	
	@Override
    protected Dialog onCreateDialog(int id) {
		
		LayoutInflater factory = LayoutInflater.from(context);
	   	textEntryView = factory.inflate(R.layout.birthday, null);
	   	txtName =(EditText)textEntryView.findViewById(R.id.name);
		datePicker = (DatePicker)textEntryView.findViewById(R.id.DatePicker01);
		radioGroup = (RadioGroup)textEntryView.findViewById(R.id.dayType);
	   	chinaDay = (RadioButton)textEntryView.findViewById(R.id.chinaDay);
	   	commonDay = (RadioButton)textEntryView.findViewById(R.id.commonDay);
	   	
	   	
	   	
	   	datePicker.init(1980, 0, 1, onDateChangedListener);	   	
	   	radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch(checkedId){
				case R.id.chinaDay:					
					birthdayType = Constants.CHINA_TYPE;
					break;
				case R.id.commonDay:
					birthdayType = Constants.COMMON_TYPE;
					break;
				}
				
			}	   		
	   	});
//	   	initBirthdayPick();
	   
        switch (id) {
       
        case DIALOG_ADD_MEMO:	        	
            return new AlertDialog.Builder(ViewMemoList.this)
//                .setIcon(R.drawable.alert_dialog_icon)
                .setTitle("新增生日备忘")
                .setView(textEntryView)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	//构造数据，插入数据库
                    	ContentValues values = new ContentValues();
                    	values.put("person_name", txtName.getText().toString());
                    	values.put("flag", birthdayType);
                    	String birthday = mYear+"-"+formatTime(mMonth+1)+"-"+formatTime(mDay);
                    	String birth_yin = "";
                    	String birth_yang = "";
                    	if(birthdayType == Constants.CHINA_TYPE ){
                    		birth_yin = birthday;
                    		birth_yang = DateBean.getGregorianCalendar(birthday);
                    	}else{
                    		birth_yang = birthday;
                    		birth_yin = DateBean.getLunarCalendar(birthday);
                    	}
                    	values.put("birth_yin",birth_yin);
                    	values.put("birth_yang",birth_yang);
                    	context.getContentResolver().insert(Constants.URI_MEMO, values);
                    	refreshData();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked cancel so do some stuff */
                    }
                })
                .create();
        case DIALOG_EDIT_MEMO:
        	return new AlertDialog.Builder(ViewMemoList.this)
//          .setIcon(R.drawable.alert_dialog_icon)
          .setTitle("新增生日备忘")
          .setView(textEntryView)
          .setPositiveButton("确定", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int whichButton) {
              	//构造数据，插入数据库
              	ContentValues values = new ContentValues();
              	values.put("person_name", txtName.getText().toString());
              	values.put("flag", birthdayType);
              	String birthday = mYear+"-"+formatTime(mMonth+1)+"-"+formatTime(mDay);
              	String birth_yin = "";
              	String birth_yang = "";
              	if(birthdayType == Constants.CHINA_TYPE ){
              		birth_yin = birthday;
              		birth_yang = DateBean.getGregorianCalendar(birthday);
              	}else{
              		birth_yang = birthday;
              		birth_yin = DateBean.getLunarCalendar(birthday);
              	}
              	values.put("birth_yin",birth_yin);
              	values.put("birth_yang",birth_yang);
              	context.getContentResolver().update(Constants.URI_MEMO, values, "_id = ?", new String[]{String.valueOf(curId)});
              	refreshData();
              }
          })
          .setNegativeButton("取消", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int whichButton) {

                  /* User clicked cancel so do some stuff */
              }
          })
          .create();
            
        	
        }
        return null;
   }
	
	private static String formatTime(int val){
		if(val>10){
			return String.valueOf(val);
		}else{
			return "0"+val;
		}
	}
	
	
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
    	super.onCreateContextMenu(menu, v, menuInfo);
    	menu.add(0, MENU_DEL, 0, "删除");
    	menu.add(0, MENU_EDIT, 0, "修改");
    }
    
    public boolean onContextItemSelected (MenuItem item) {
    	super.onContextItemSelected(item);
    	switch(item.getItemId()){
    	case MENU_DEL:
    		//
    		if(curId != 0){
    			getContentResolver().delete(Constants.URI_MEMO, "_id ="+curId, null);
    			refreshData();
    		}
    		
    		break;
    	case MENU_EDIT:
    		ViewMemoList.this.showDialog(DIALOG_EDIT_MEMO);
    		break;
    	}
    	
    	return false;
    }
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		
    	MenuInflater inflater = getMenuInflater();
    	inflater.inflate(R.menu.menu_memo, menu);
    	return true;
	}
    
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {
    	
    	switch (item.getItemId()) {
		case R.id.menu_add_memo:
			//弹出新增窗口
			ViewMemoList.this.showDialog(DIALOG_ADD_MEMO);
			break;		
		default:
			throw new IllegalArgumentException("Unknown Operator");
		}
    	return true;
    }
	
	

}
